package com.dx.mes.common.transcoder.util;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.springframework.stereotype.Component;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;

@Component
public class MqOpe {
    public static final String XML_HEADER = "<?xml version='1.0' encoding='UTF-8' ?>";
	/**
	 * 特殊字符转换 spacialChars为特殊字符， validChars为将要转换的字符。这两个数组是一一对应的
	 */
	private static String[] spacialChars = { "&", "<", ">", "\"", "'" };
	private static String[] validChars = { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;" };
	
	public static Object inStr2Obj(String strInMsg, Object inObj) {
		Object objIn = new Object();
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("transaction", inObj.getClass());
		xstream.processAnnotations(inObj.getClass());
		objIn = xstream.fromXML(strInMsg);
		return objIn;
	}

	public static String obj2Str(Object inObj) {
		String relsultXml = null;
		OutputStream output = new ByteArrayOutputStream();
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("transaction", inObj.getClass());
		xstream.autodetectAnnotations(true);
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.marshal(inObj, new CompactWriter(new OutputStreamWriter(output)));
		relsultXml = output.toString().replace("__", "_");// .replace("<id><","<").replace("></id>",">");

		// writeQuery(relsultXml, inObj.getClass().getSimpleName());

		return relsultXml;
	}
	


    public static String obj2Xml(Object obj, String rootElement) {
        StringBuffer buffer = new StringBuffer(XML_HEADER);
        buffer.append("\n");
        XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder()));
        xstream.alias(rootElement, obj.getClass());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.autodetectAnnotations(true);
        buffer.append(xstream.toXML(obj));
        return replaceSpecialChar(buffer.toString());
    }

    public static Object xml2Obj(String xmlStr, Class clazz) {
        XStream xstream = new XStream(new DomDriver());
        xstream.processAnnotations(clazz);
        xstream.registerConverter(new DoubleConverter());
        xstream.registerConverter(new IntConverter());
        return xstream.fromXML(xmlStr);
    }
    
	/**
	 * 转换特殊字符
	 * @param s
	 * @return
	 */
	private static String replaceSpecialChar(String s) {
		for (int i = 0; i < validChars.length; i++) {
			s = s.replaceAll(validChars[i], spacialChars[i]);
		}
		return s;
	}
}
